﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
using System.Data;
using System.Reflection;

using Krs.Ats.IBNet;
using Krs.Ats.IBNet.Contracts;

using Forex.IB.RealTimeBars.WinApp.Extensions;
using Forex.IB.RealTimeBars.Components;





namespace Forex.IB.RealTimeBars.WinApp
{
    delegate void SetTextCallback(string text);

    public partial class RealTimeData : Form
    {
        private bool m_isExiting;
        ConnectionParametersVO connParameter = new ConnectionParametersVO();
        IBClient client = new IBClient();
        private static bool FlagReqMarketData = false;
        private static bool isLoad = true;
        private static Contract IdealPro;
        static System.Windows.Forms.Timer RealTimeDataTimer = new System.Windows.Forms.Timer();
        DateTime lastRunTime;
        static System.Windows.Forms.Timer OrderTimer = new System.Windows.Forms.Timer();
        private static Contract contract;
        private static Order BuyContract;
        private List<Thread> _workers = new List<Thread>();
        delegate void SetLastUpdate(DataTable dt);
        delegate void SetDisplayOrders(DataTable dt);
        delegate void SetFillIChimokuIndicators(DataTable dt);
        private static int NextOrderId = 0;
        private static RealTimeData mainFormForLogging;
        public static RealTimeData MainFormForLogging
        {
            get
            {
                return mainFormForLogging;
            }
        }

        public RealTimeData()
        {
            InitializeComponent();
            if (mainFormForLogging == null)
            {
                mainFormForLogging = this;
            }

            this.Load += new EventHandler(Form1_Load);

            client.CurrentTime += client_CurrentTime;
            client.RealTimeBar += client_RealTimeBar;
            client.Error += client_Error;
            client.NextValidId += client_NextValidId;
            client.OrderStatus += client_OrderStatus;
            client.HistoricalData += client_HistoricalData;
            client.ThrowExceptions = true;
            this.FormClosing += new FormClosingEventHandler(this.RealTimeData_FormClosing);

            RealTimeDataTimer.Tick += new EventHandler(RealTimeDataTimerEventProcessor);
            // Sets the timer interval to 1 seconds.
            RealTimeDataTimer.Interval = 60000;
            RealTimeDataTimer.Start();

            OrderTimer.Tick += new EventHandler(OrderTimerEventProcessor);
            // Sets the timer interval to 1 seconds.
            OrderTimer.Interval = 30000;
            OrderTimer.Start();
        }

        #region Form Methods
        private void RealTimeData_Resize(object sender, EventArgs e)
        {
            try
            {
                if (FormWindowState.Minimized == this.WindowState)
                {
                    notifyIcon1.Visible = true;
                    notifyIcon1.ShowBalloonTip(500);
                    this.Hide();
                }
                else if (FormWindowState.Normal == this.WindowState)
                {
                    notifyIcon1.Visible = false;
                }
            }
            catch (Exception ex)
            {
                this.txtErrorMsg.WriteLine("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());
            }

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void RealTimeData_Load(object sender, EventArgs e)
        {
        }

        private void RealTimeData_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!m_isExiting)
            {
                DialogResult frmclose = MessageBox.Show("Do you really want to exit Forex Trading?", "Closing...", MessageBoxButtons.YesNo);
                if (frmclose == DialogResult.No)
                {
                    e.Cancel = true;
                }
                if (frmclose == DialogResult.Yes)
                {
                    if (OrderTimer.Enabled)
                    {
                        OrderTimer.Stop();
                    }
                    if (RealTimeDataTimer.Enabled)
                    {
                        RealTimeDataTimer.Stop();
                    }
                    if (client.Connected)
                    {
                        client.Disconnect();
                        client = null;
                    }
                    foreach (Thread t in _workers)
                    {
                        if (t.IsAlive)
                            t.Abort();
                    }
                    m_isExiting = true;
                    Application.Exit();
                }
            }
        }

        private void Form1_Load(System.Object sender, System.EventArgs e)
        {

        }
        #endregion

        #region Button events
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = new DialogResult();
                ConnectionParameters cP = new ConnectionParameters();
                dr = cP.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    connParameter.PortNumber = int.Parse(cP.txtPortNumber.Text);
                    connParameter.ClientId = int.Parse(cP.txtClientId.Text);
                    connectClient();

                    lblStatus.Text = "IB Client Connected";
                    lblStatus.ForeColor = Color.Green;

                    if (!OrderTimer.Enabled)
                    {
                        OrderTimer.Start();
                    }
                    if (!RealTimeDataTimer.Enabled)
                    {
                        RealTimeDataTimer.Start();
                    }
                }
                else if (dr == DialogResult.Cancel)
                    txtErrorMsg.Text += "Failed to connect. Please provide valid client id and port number.";
                cP.Close();
            }

            catch (Exception ex)
            {
                this.txtErrorMsg.WriteLine("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());
            }
        }

        //private void btnDisconnect_Click(object sender, EventArgs e)
        //{

        //    try
        //    {
        //        if (MessageBox.Show("Do you want to disconnect?", "Disconnecting...", MessageBoxButtons.YesNo) == DialogResult.Yes)
        //        {
        //            if (client.Connected)
        //            {
        //                client.Disconnect();
        //                client = null;
        //                this.txtTWSResponses.WriteLine("Successfully disconnected.");
        //                lblStatus.Text = "IB Client Disconnected";
        //                lblStatus.ForeColor = Color.Red;

        //                OrderTimer.Stop();
        //                RealTimeDataTimer.Stop();

        //            }
        //            else
        //            {
        //                this.txtTWSResponses.WriteLine("Already disconnected.");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.txtErrorMsg.WriteLine("Error Message :" + ex.Message.ToString());
        //    }
        //}

        private void btn_placeOrder_Click(object sender, EventArgs e)
        {
            // SqlHelper helper = new SqlHelper();
            DataTable dt = new DataTable();
            try
            {
                //Get tickers
                FlagReqMarketData = true;
                SqlHelper helper = new SqlHelper();
                helper.StartUpRoutine();
                // dt = helper.GetTickers();
                if (client.Connected)
                {
                    //     this.txtTWSResponses.WriteLine("Connecting to Real Time Ticks Data Server.");
                    //Parallel.ForEach(dt.AsEnumerable(), row =>
                    //{
                    //   string[] forexTickers = row["Ticker"].ToString().Split('/');
                    // Krs.Ats.IBNet.Contracts.Forex frx = new Krs.Ats.IBNet.Contracts.Forex(forexTickers[0], forexTickers[1]);
                    //client.RequestRealTimeBars(int.Parse(row["Ticker_Id"].ToString()), frx, 5, RealTimeBarType.Midpoint, false);
                    //  });

                    HistoricaData histData = new HistoricaData(connParameter);
                    Thread oThread = new Thread(new ThreadStart(histData.GetHistoricalData));
                    _workers.Add(oThread);
                    oThread.IsBackground = true;
                    oThread.Start();
                    Thread.Sleep(1500);
                    Thread tLoadHisMinData = new Thread(new ThreadStart(LoadHisMinData));
                    _workers.Add(tLoadHisMinData);
                    tLoadHisMinData.IsBackground = true;
                    tLoadHisMinData.Start();
                }
                else
                {
                    this.txtErrorMsg.WriteLine("Please connect the client. Client already disconnected or no connectivity with TWS.");
                }
            }
            catch (Exception ex)
            {
                this.txtErrorMsg.WriteLine("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());
            }
        }

        private void btn_CancelPlaceOrder_Click(object sender, EventArgs e)
        {
            SqlHelper helper = new SqlHelper();
            DataTable dt = new DataTable();
            try
            {
                //Get tickers
                this.txtTWSResponses.WriteLine("Disconnecting from Data Server.");
                isLoad = false;
                dt = helper.GetTickers();
                if (client.Connected)
                {
                    Parallel.ForEach(dt.AsEnumerable(), row =>
                    {
                        string[] forexTickers = row["Ticker"].ToString().Split('/');
                        // client.CancelRealTimeBars(int.Parse(row["Ticker_Id"].ToString()));
                        client.CancelHistoricalData(int.Parse(row["Ticker_Id"].ToString()));
                    });
                    this.txtTWSResponses.WriteLine("All the request has been canceled.....");
                }
                else
                {
                    this.txtErrorMsg.WriteLine("Please connect the client. Client already disconnected.");
                }
                FlagReqMarketData = false;
            }
            catch (Exception ex)
            {
                this.txtErrorMsg.WriteLine("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());
            }
        }

        //private void btnExportIchimoku_Click(object sender, EventArgs e)
        //{
        //    Export2Excel(this.gvIChimoku, true);
        //}

        //private void btndisplayIchimoku_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        SqlHelper helper = new SqlHelper();
        //        this.FillIChimokuIndicators(helper.GetIChimomuIndicators(DateTime.Parse(dtFrom.Value.ToString()), DateTime.Parse(dtTo.Value.ToString())));
        //    }
        //    catch (Exception ex)
        //    {
        //        this.SetErrorReponses("Error Message :" + ex.Message.ToString());
        //    }
        //}
        private void LoadHisMinData()
        {
            SqlHelper helper = new SqlHelper();
            DataTable dt = new DataTable();

            dt = helper.GetTickers();
            this.txtTWSResponses.WriteLine("Time: " + DateTime.Now.ToString() + " Loading..data :-)");
            while (isLoad)
            {
                foreach (DataRow row in dt.Rows)
                {
                    string[] forexTickers = row["Ticker"].ToString().Split('/');
                    IdealPro = new Contract(forexTickers[0], "IDEALPRO", SecurityType.Cash, forexTickers[1]);
                    client.RequestHistoricalData(int.Parse(row["Ticker_Id"].ToString()), IdealPro, DateTime.Now.AddMinutes(-1), TimeSpan.FromSeconds(60), BarSize.OneMinute, HistoricalDataType.Midpoint, 1);
                }
                Thread.Sleep(60000);
            }
        }

        #endregion

        #region Private Methods
        private void connectClient()
        {
            if (client == null)
            {
                client = new IBClient();
                client.CurrentTime += client_CurrentTime;
                client.RealTimeBar += client_RealTimeBar;
                client.Error += client_Error;
                client.ThrowExceptions = true;
            }
            this.txtTWSResponses.WriteLine("Connecting to IB.");
            client.Connect("127.0.0.1", connParameter.PortNumber, connParameter.ClientId);
            client.RequestCurrentTime();
        }

        private void client_CurrentTime(object sender, CurrentTimeEventArgs e)
        {
            this.SetTWSResponses("Connected at (UTC Time): " + e.Time.ToString());
            LogFile.LogMessage("Connected at (UTC Time): " + e.Time.ToString());
        }

        private void client_NextValidId(object sender, NextValidIdEventArgs e)
        {
            Console.WriteLine("Next Valid Id: " + e.OrderId);
            NextOrderId = e.OrderId;
        }

        private void client_Error(object sender, ErrorEventArgs e)
        {
            this.txtErrorMsg.WriteLine(e.ErrorMsg);
            LogFile.LogMessage(e.ErrorMsg);
        }

        private void client_RealTimeBar(object sender, RealTimeBarEventArgs e)
        {
            SqlHelper helper = new SqlHelper();
            helper.AddRealTimeBarsData(int.Parse(e.RequestId.ToString()), DateTime.Now, double.Parse(e.Open.ToString()), double.Parse(e.Close.ToString()), double.Parse(e.High.ToString()), double.Parse(e.Low.ToString()), long.Parse(e.Volume.ToString()));
            lastRunTime = DateTime.Now;
        }

        private void client_HistoricalData(object sender, HistoricalDataEventArgs e)
        {
            lock (this)
            {
                SqlHelper helper = new SqlHelper();
                helper.AddHistoricalData(e.RequestId, DateTime.Parse(e.Date.ToString()), double.Parse(e.Open.ToString()), double.Parse(e.Close.ToString()), double.Parse(e.High.ToString()), double.Parse(e.Low.ToString()), long.Parse(e.Volume.ToString()));
                // Console.WriteLine("Date: " + e.Date + " Open: " + e.Open + " Close: " + e.Close + " Date: " + e.Date + " High: " + e.High + " Low: " + e.Low);
                lastRunTime = DateTime.Now;
            }
        }

        private void client_OrderStatus(object sender, OrderStatusEventArgs e)
        {
            try
            {
                SqlHelper helper = new SqlHelper();

                if (e.OrderId > 0)
                {
                    string sWhyHld = string.Empty;
                    if (string.IsNullOrEmpty(e.WhyHeld))
                    {
                        sWhyHld = string.Empty;
                    }
                    else
                    {
                        sWhyHld = e.WhyHeld;
                    }
                    helper.UpdateOrderStatus(e.OrderId, e.Status.ToString(), e.Remaining.ToString(), decimal.Parse(e.AverageFillPrice.ToString()), decimal.Parse(e.LastFillPrice.ToString()), sWhyHld);
                    SetTWSResponses("OrderID :" + e.OrderId.ToString() + " Status: " + e.Status.ToString() + " Average Fill Price: " + e.AverageFillPrice.ToString() + " Last Fill Price: " + e.LastFillPrice.ToString());
                    LogFile.LogMessage("OrderID :" + e.OrderId.ToString() + " Status: " + e.Status.ToString() + " Average Fill Price: " + e.AverageFillPrice.ToString() + " Last Fill Price: " + e.LastFillPrice.ToString());
                }
                if (e.Status == OrderStatus.Canceled)
                {
                    if (e.OrderId > 0)
                    {
                        DataTable odt = new DataTable();
                        odt = helper.GetOrderByOrderId(e.OrderId);
                        DataRow row = odt.Rows[0];
                        helper.UpdateTickersIn(row["Ticker"].ToString(), false);
                        LogFile.LogMessage("Order Canceled. " + " OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString());
                    }
                }

                if (e.Status == OrderStatus.Filled)
                {
                    if (e.OrderId > 0)
                    {
                        DataTable odt = new DataTable();
                        odt = helper.GetOrderByOrderId(e.OrderId);
                        DataRow row = odt.Rows[0];
                        if (string.IsNullOrEmpty(row["Order_RefId"].ToString()))
                        {
                            helper.AddOrderRequest(row["Ticker"].ToString(), ActionSide.Sell.ToString(), (e.LastFillPrice + 6 * decimal.Parse(row["Pip"].ToString())), 50000, e.OrderId, decimal.Parse(row["Pip"].ToString()), "Profit Order");
                            helper.AddOrderRequest(row["Ticker"].ToString(), ActionSide.Sell.ToString(), (e.LastFillPrice - 8 * decimal.Parse(row["Pip"].ToString())), 50000, e.OrderId, decimal.Parse(row["Pip"].ToString()), "Loss Order");
                        }
                        if (string.Equals(row["ActionSide"].ToString(), "Sell"))
                        {
                            helper.UpdateTickersIn(row["Ticker"].ToString(), false);
                            LogFile.LogMessage("OrderID :" + e.OrderId.ToString() + " Type: Sell" + " Status: " + e.Status.ToString() + " Average Fill Price: " + e.AverageFillPrice.ToString() + " Last Fill Price: " + e.LastFillPrice.ToString());
                        }
                        if (string.Equals(row["ActionSide"].ToString(), "Buy"))
                        {
                            LogFile.LogMessage("OrderID :" + e.OrderId.ToString() + " Type: Buy" + " Status: " + e.Status.ToString() + " Average Fill Price: " + e.AverageFillPrice.ToString() + " Last Fill Price: " + e.LastFillPrice.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.SetErrorReponses("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());
            }
        }

        // This is the method to run when the timer is raised.
        private void RealTimeDataTimerEventProcessor(Object myObject, EventArgs myEventArgs)
        {
            RealTimeDataTimer.Stop();
            RealTimeDataTimer.Enabled = true;
            SqlHelper helper = new SqlHelper();
            try
            {
                FillLastUpdate((new SqlHelper()).LastUpdated());
                FillDisplayOrders((new SqlHelper()).DisplayOrders());

                //Send out the Latest Trade Notifications
                DataTable tndt = helper.GetListUnprocessedTradeNotify();
                if (tndt.Rows.Count > 0)
                {
                    foreach (DataRow row in tndt.Rows)
                    {
                        DataTable odt = new DataTable();
                        odt = helper.GetOrderByOrderId(int.Parse(row["OrderId"].ToString()));
                        DataRow odRow = odt.Rows[0];
                        if (string.Equals(odRow["ActionSide"].ToString(), "Sell"))
                        {
                            (new SendEmail()).TradeNotify(Common.To, Common.Cc, Common.Bcc, "Order filled for Ticker " + odRow["Ticker"].ToString(), "Order filled, type sell." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + odRow["Ticker"].ToString() + " TotalQuantity: " + odRow["Quantity"].ToString() + "AverageFillPrice: " + odRow["AverageFillPrice"].ToString(), Common.smtpclient);
                        }
                        if (string.Equals(odRow["ActionSide"].ToString(), "Buy"))
                        {
                            (new SendEmail()).TradeNotify(Common.To, Common.Cc, Common.Bcc, "Order filled for Ticker " + odRow["Ticker"].ToString(), "Order filled, type buy." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + odRow["Ticker"].ToString() + " TotalQuantity: " + odRow["Quantity"].ToString() + "AverageFillPrice: " + odRow["AverageFillPrice"].ToString(), Common.smtpclient);
                        }
                        helper.UpdateTradeNotify(int.Parse(row["OrderId"].ToString()));
                    }
                }

                DataTable triggerdt = helper.GetListUnprocessedTriggerNotify();
                if (triggerdt.Rows.Count > 0)
                {
                    foreach (DataRow row in triggerdt.Rows)
                    {
                        (new SendEmail()).TradeNotify(Common.To, Common.Cc, Common.Bcc, "Buy Trigger for " + row["Ticker"].ToString() + " at " + row["TriggerDateTime"].ToString(), "Buy Trigger for " + row["Ticker"].ToString() + " at " + row["TriggerDateTime"].ToString(), Common.smtpclient);
                        helper.UpdateTriggerNotify(int.Parse(row["Id"].ToString()));
                    }
                }

                if (FlagReqMarketData)
                {

                    TimeSpan timeSinceLastRun = DateTime.Now.Subtract(lastRunTime);

                    if (timeSinceLastRun.Minutes > 2)
                    {
                        DataTable dt = new DataTable();
                        try
                        {
                            //Get tickers
                            this.txtTWSResponses.WriteLine("Disconnecting from Real Time Ticks Data Server, no response received for 2 minutes.");
                            dt = helper.GetTickers();
                            if (client.Connected)
                            {
                                Parallel.ForEach(dt.AsEnumerable(), row =>
                                {
                                    string[] forexTickers = row["Ticker"].ToString().Split('/');
                                    client.CancelHistoricalData(int.Parse(row["Ticker_Id"].ToString()));
                                });
                                this.txtTWSResponses.WriteLine("All the request has been canceled.....");

                                //Initiate to connect again

                                Parallel.ForEach(dt.AsEnumerable(), row =>
                                {
                                    string[] forexTickers = row["Ticker"].ToString().Split('/');
                                    //Krs.Ats.IBNet.Contracts.Forex frx = new Krs.Ats.IBNet.Contracts.Forex(forexTickers[0], forexTickers[1]);
                                    //client.RequestRealTimeBars(int.Parse(row["Ticker_Id"].ToString()), frx, 5, RealTimeBarType.Midpoint, false);
                                    IdealPro = new Contract(forexTickers[0], "IDEALPRO", SecurityType.Cash, forexTickers[1]);
                                    client.RequestHistoricalData(int.Parse(row["Ticker_Id"].ToString()), IdealPro, DateTime.Now.AddMinutes(-1), TimeSpan.FromSeconds(60), BarSize.OneMinute, HistoricalDataType.Midpoint, 1);

                                });

                                this.txtTWSResponses.WriteLine("All the request has been reconnected.....");

                            }
                            else
                            {
                                this.txtErrorMsg.WriteLine("Please connect the client. Client already disconnected.");
                            }

                        }
                        catch (Exception ex)
                        {
                            this.txtErrorMsg.WriteLine("Error Message :" + ex.Message.ToString());
                            LogFile.LogMessage(ex.Message.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.SetErrorReponses("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());

            }
        }

        private void OrderTimerEventProcessor(Object myObject, EventArgs myEventArgs)
        {
            OrderTimer.Stop();
            OrderTimer.Enabled = true;
            client.RequestAllOpenOrders();
            try
            {
                SqlHelper helper = new SqlHelper();
                DataTable dt = new DataTable();
                dt = helper.GetListUnprocessedOrders();
                DataTable dtCancel = new DataTable();
                dtCancel = helper.GetListOrdersToBeCancelled();

                foreach (DataRow row in dtCancel.Rows)
                {
                    client.CancelOrder(int.Parse(row["OrderId"].ToString()));
                }

                foreach (DataRow row in dt.Rows)
                {
                    if (string.Equals(row["ActionSide"].ToString(), "Buy"))
                    {
                        string[] forexTickers = row["Ticker"].ToString().Split('/');
                        contract = new Contract(forexTickers[0], "IDEALPRO", SecurityType.Cash, forexTickers[1]);
                        BuyContract = new Order();
                        BuyContract.Action = ActionSide.Buy;
                        BuyContract.OutsideRth = true;
                        BuyContract.LimitPrice = decimal.Parse(row["Price"].ToString());
                        BuyContract.OrderType = OrderType.Limit;
                        BuyContract.TotalQuantity = int.Parse(row["Quantity"].ToString());
                        client.PlaceOrder(int.Parse(row["OrderId"].ToString()), contract, BuyContract);
                        helper.UpdateOrderExecutionStarted(int.Parse(row["OrderId"].ToString()), true);
                        SetTWSResponses("Order Placed." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString());
                        LogFile.LogMessage("Order Placed." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString());
                        //  (new SendEmail()).TradeNotify(Common.To, Common.Cc, Common.Bcc, "Order placed for Ticker " + row["Ticker"].ToString(), "Order placed, type buy." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString(), Common.smtpclient);

                    }
                    if (string.Equals(row["ActionSide"].ToString(), "Sell"))
                    {
                        string[] forexTickers = row["Ticker"].ToString().Split('/');
                        contract = new Contract(forexTickers[0], "IDEALPRO", SecurityType.Cash, forexTickers[1]);
                        BuyContract = new Order();
                        BuyContract.Action = ActionSide.Sell;
                        BuyContract.OutsideRth = true;
                        BuyContract.LimitPrice = decimal.Parse(row["Price"].ToString());
                        BuyContract.OrderType = OrderType.Limit;
                        BuyContract.TotalQuantity = int.Parse(row["Quantity"].ToString());
                        client.PlaceOrder(int.Parse(row["OrderId"].ToString()), contract, BuyContract);
                        helper.UpdateOrderExecutionStarted(int.Parse(row["OrderId"].ToString()), true);
                        SetTWSResponses("Order Placed." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString());
                        LogFile.LogMessage("Order Placed." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString());
                        //   (new SendEmail()).TradeNotify(Common.To, Common.Cc, Common.Bcc, "Order placed for Ticker " + row["Ticker"].ToString(), "Order placed, type sell." + "OrderID :" + row["OrderId"].ToString() + " Ticker: " + row["Ticker"].ToString() + " TotalQuantity: " + row["Quantity"].ToString() + " Price: " + row["Price"].ToString(), Common.smtpclient);
                    }
                }
            }
            catch (Exception ex)
            {
                SetErrorReponses("Error Message :" + ex.Message.ToString());
                LogFile.LogMessage(ex.Message.ToString());
            }
        }

        private void SetTWSResponses(string text)
        {
            if (this.txtTWSResponses.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetTWSResponses);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtTWSResponses.WriteLine(text);
            }
        }

        public void SetHistoricalDataStatus(string text)
        {
            if (this.txtHisDataStatusUpdt.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetHistoricalDataStatus);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtHisDataStatusUpdt.WriteLine(text);
            }
        }

        private void SetErrorReponses(string text)
        {
            if (this.txtErrorMsg.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetErrorReponses);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtErrorMsg.Text = text;
            }
        }

        private void FillLastUpdate(DataTable dt)
        {
            if (this.dgLastUpdate.InvokeRequired)
            {
                SetLastUpdate d = new SetLastUpdate(FillLastUpdate);
                this.Invoke(d, new object[] { dt });
            }
            else
            {
                if (dt.Rows.Count > 0)
                {
                    this.dgLastUpdate.DataSource = dt;
                }
            }
        }


        private void FillDisplayOrders(DataTable dt)
        {
            if (this.dgOrders.InvokeRequired)
            {
                SetDisplayOrders d = new SetDisplayOrders(FillDisplayOrders);
                this.Invoke(d, new object[] { dt });
            }
            else
            {
                if (dt.Rows.Count > 0)
                {
                    this.dgOrders.DataSource = dt;
                }
            }
        }

        #endregion
    }
}
